<?php


namespace liuqiang\captcha;


class captcha
{
    public $width;
    public $height;
    public $length;
    public $code;
    public $img;

    public function __construct($code = '', $width = 70, $height = 25)
    {
        $this->height = $height;
        $this->width = $width;
        $this->code = $code;
        $this->img = imagecreatetruecolor($this->width, $this->height);
    }

    public function createImg($code = '')
    {
        if (!$code)
            $code = $this->code;
        if (!$code)
            throw new \InvalidArgumentException("生成验证码code不能为空");
        imagefill($this->img, 0, 0, imagecolorallocate($this->img, 255, 255, 255));
        for ($i = 0; $i < 20; $i++) { //干扰线
            $color = imagecolorallocate($this->img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
            imageline($this->img, mt_rand(0, $this->width), mt_rand(0, $this->height), mt_rand(0, $this->width), mt_rand(0, $this->height), $color);
        }
        for ($i = 0; $i < 200; $i++) { //背景
            $color = imagecolorallocate($this->img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
            imagestring($this->img, 1, mt_rand(1, $this->width), mt_rand(1, $this->height), '*', $color);
        }
        $len = mb_strlen($this->code, 'utf-8');
        $size = $this->width / $len - 3;
        for ($i = 0; $i < strlen($code); $i++) { //验证码
            $color = imagecolorallocate($this->img, mt_rand(0, 100), mt_rand(0, 150), mt_rand(0, 200));
            imagettftext($this->img, $size, mt_rand(-50, 50), $i * $size + 5, $this->height - 5, $color
                , dirname(__FILE__) . '/../font/5.ttf', $code[$i]);
        }
        ob_start();
        imagepng($this->img);
        $result = ob_get_contents();
        ob_end_clean();
        imagedestroy($this->img);
        return ['image' => 'data:image/png;base64,' . base64_encode($result)];
    }
}